import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QStackedWidget, QLineEdit


class App(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('Stacked Widget Example')

        # 创建堆栈窗口
        self.stackedWidget = QStackedWidget(self)
        self.stackedWidget.setGeometry(10, 10, 280, 160)

        # 创建两个窗口（实际上是QWidget）
        self.page1 = QWidget()
        self.page2 = QWidget()

        # 设置布局和按钮
        layout1 = QVBoxLayout()
        text = QLineEdit('我是第1页')
        btn1 = QPushButton('Go to Page 2', self)
        btn1.clicked.connect(self.nextPage)
        layout1.addWidget(text)
        layout1.addWidget(btn1)
        self.page1.setLayout(layout1)

        layout2 = QVBoxLayout()
        btn2 = QPushButton('Go to Page 1', self)
        btn2.clicked.connect(self.previousPage)
        layout2.addWidget(btn2)
        self.page2.setLayout(layout2)

        # 将页面添加到堆栈中
        self.stackedWidget.addWidget(self.page1)
        self.stackedWidget.addWidget(self.page2)

    def nextPage(self):
        self.stackedWidget.setCurrentIndex(self.stackedWidget.currentIndex() + 1)

    def previousPage(self):
        self.stackedWidget.setCurrentIndex(self.stackedWidget.currentIndex() - 1)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    ex.show()
    sys.exit(app.exec_())